//
//  Product_add_two_ble_vc.m
//  ainkjj
//
//  Created by zhiyiLiu on 2020/3/9.
//  Copyright © 2020 zhiyiLiu. All rights reserved.
//

#import "Product_add_two_ble_vc.h"
#import "Product_add_two_wifi_vc.h"
#import "Product_add_three_adding_vc.h"

#import "UIButton+SSEdgeInsets.h"
#import "MMAlertView.h"
#import "LQFoldButtonCell.h"
#import "LQFoldButtonItem.h"

#import <CoreBluetooth/CoreBluetooth.h>


#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <SystemConfiguration/CaptiveNetwork.h>

#import <CoreLocation/CoreLocation.h>
#import <NetworkExtension/NetworkExtension.h>

@interface Product_add_two_ble_vc ()<CLLocationManagerDelegate, UITableViewDelegate,UITableViewDataSource>
{
    CGSize __foldContentSize;
    BOOL __isFolded;
    BOOL __ble_isFolded;
    
    CGRect __originRect;
    NSMutableArray *peripheralDataArray;
    BabyBluetooth *baby;
    
    
}

@property (weak, nonatomic) IBOutlet UIButton *bg_btn;
@property (weak, nonatomic) IBOutlet UIButton *ble_bg_btn;
@property (weak, nonatomic) IBOutlet UIImageView *tip_iv;
@property (weak, nonatomic) IBOutlet UITextField *pwd_tf;
@property (weak, nonatomic) IBOutlet UILabel *wifi_name_lb;
@property (weak, nonatomic) IBOutlet UILabel *ble_name_lb;
@property (nonatomic, copy) NSString *apBssid;

@property (strong, nonatomic) CLLocationManager *locationManager;
@property (weak, nonatomic) IBOutlet UITableView *ble_foldTable;

@property (weak, nonatomic) IBOutlet UITableView *foldTable;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *foldTable_height;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *ble_foldTable_height;
@property (nonatomic, strong)NSMutableArray *dataSource;
@property (nonatomic, assign)NSInteger selectedIndex;
@property (nonatomic, assign)CGFloat contentHeight;
@property (nonatomic, assign)CGFloat itemHeight;


@property (nonatomic, strong)NSDictionary *item;
@end


@implementation Product_add_two_ble_vc
- (IBAction)ble_bg_btn_click:(UIButton *)sender {
    sender.userInteractionEnabled = NO;
    sender.selected = !sender.selected;
    if (__ble_isFolded) {
        [self ble_tb_close];
    } else {
        [self ble_tb_open];
    }
    
    sender.userInteractionEnabled = YES;
}
- (IBAction)bg_btn_click:(UIButton *)sender {
    sender.userInteractionEnabled = NO;
    sender.selected = !sender.selected;
    if (__isFolded) {
        [self close];
    } else {
        [self open];
    }
    
    sender.userInteractionEnabled = YES;
}
- (IBAction)next_action:(UIButton *)sender {
    
    if (self.ble_name_lb.text.length ==0) {
        [MBProgressHUD showInfoMessage:@"请确认设备的蓝牙名称"];
        return;
    }
    if (self.wifi_name_lb.text.length ==0) {
        [MBProgressHUD showInfoMessage:@"请确认WiFi名称"];
        return;
    }
    if (self.pwd_tf.text.length == 0) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"您输入的密码为空，请再次确认" message:nil   preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"返回" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [self.pwd_tf becomeFirstResponder];
        }];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self push];
            
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else{
        [self push];
    }
    
    
}

- (void)push{
    Product_add_three_adding_vc *vc= [[Product_add_three_adding_vc alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    
    CBPeripheral *peripheral = [self.item objectForKey:@"peripheral"];
    vc.currPeripheral = peripheral;
    
    
    //停止扫描
    [baby cancelScan];
    
    vc.aDevice =self.aDevice;
    
    vc.wifi_name = self.wifi_name_lb.text;
    vc.pwd = self.pwd_tf.text;
    vc.ble_name = self.ble_name_lb.text;
    
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (IBAction)pwd_tf_see_action:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.pwd_tf.secureTextEntry = !self.pwd_tf.secureTextEntry;
}
- (void)ble_setup{
    peripheralDataArray = [[NSMutableArray alloc]init];
    
    //初始化BabyBluetooth 蓝牙库
    baby = [BabyBluetooth shareBabyBluetooth];
    //设置蓝牙委托
    [self babyDelegate];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    //停止之前的连接
    [baby cancelAllPeripheralsConnection];
    //设置委托后直接可以使用，无需等待CBCentralManagerStatePoweredOn状态。
    baby.scanForPeripherals().begin();
    //baby.scanForPeripherals().begin().stop(10);
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
}
- (void)dealloc{
    self.foldTable.delegate = nil;
    self.ble_foldTable.delegate = nil;
    
    //停止扫描
    [baby cancelScan];
    baby = nil;
    
    DLog();
}
- (void)wifi_page{
    Product_add_two_wifi_vc *vc= [[Product_add_two_wifi_vc alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.aDevice = self.aDevice;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)initSubviews{
    [super initSubviews];
    self.title = @"蓝牙配网";

}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Wi-Fi配网" style:UIBarButtonItemStylePlain target:self action:@selector(wifi_page)];

    
    DLog(@"%@", [self getWifiName]);
    NSString *name = [self getWifiName];
    if (name.length > 0) {
        self.wifi_name_lb.text = name;
    }
    if(@available(iOS 13.0, *)){
        [self getUserLocation];
    }
    
    
    //    [MBProgressHUD showInfoMessage:@"准备打开设备"];
    
    
    [self ble_setup];
    
    
    
    
    [self.bg_btn setEdgeInsetsWithType:SSEdgeInsetsTypeImage marginType:SSMarginTypeRight margin:0];
    [self.ble_bg_btn setEdgeInsetsWithType:SSEdgeInsetsTypeImage marginType:SSMarginTypeRight margin:0];
    
    _foldTable.delegate = self;
    _foldTable.dataSource = self;
    _foldTable.backgroundColor = [UIColor whiteColor];
    [_foldTable.layer setBorderColor:UIColor.lightGrayColor.CGColor];
    _foldTable.layer.borderWidth = 0.6;
    _foldTable.tableFooterView = UIView.new;
    
    _selectedIndex = -1;
    
    
    _ble_foldTable.delegate = self;
    _ble_foldTable.dataSource = self;
    _ble_foldTable.backgroundColor = [UIColor whiteColor];
    [_ble_foldTable.layer setBorderColor:UIColor.lightGrayColor.CGColor];
    _ble_foldTable.layer.borderWidth = 0.6;
    _ble_foldTable.tableFooterView = UIView.new;
    
    
    NSArray *arr = @[@"手动输入Wi-Fi名称"];
    
    NSMutableArray *datas = [NSMutableArray arrayWithCapacity:arr.count];
    for (NSString *title in arr) {
        LQFoldButtonItem *item = [[LQFoldButtonItem alloc]init];
        item.title = title;
        [datas addObject:item];
    }
    
    self.dataSource = datas;
    
    
    [self.foldTable reloadData];
    
    
    
    
}

#pragma mark - ================== 当前WiFi名称获取 ==================
- (NSString *)getWifiName{
    
    NSString *wifiName = @"未找到当前连接的Wi-Fi";
    
    CFArrayRef myArray = CNCopySupportedInterfaces();
    
    if (myArray != nil) {
        
        CFDictionaryRef myDict =CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));
        
        if (myDict != nil) {
            
            NSDictionary *dict = (NSDictionary*)CFBridgingRelease(myDict);
            
            wifiName = [dict valueForKey:@"SSID"];
            self.apBssid = [dict valueForKey:@"BSSID"];
            CFRelease(myArray);
        }else{
            CFRelease(myArray);
        }
    }
    
    return wifiName;
}
#pragma mark - 定位授权代理方法
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse ||
        status == kCLAuthorizationStatusAuthorizedAlways) {
        //再重新获取ssid
        NSString *name = [self getWifiName];
        if (name.length > 0) {
            self.wifi_name_lb.text = name;
        }
    }
}

- (void)getUserLocation{
    if (!self.locationManager) {
        self.locationManager = [[CLLocationManager alloc] init];
    }
    //如果用户第一次拒绝了，触发代理重新选择，要用户打开位置权限
    [self.locationManager requestAlwaysAuthorization];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 1.0f;
    [self.locationManager startUpdatingLocation];
    
}
#pragma mark -蓝牙配置和操作

//蓝牙网关初始化和委托方法设置
-(void)babyDelegate{
    
    __weak typeof(self) weakSelf = self;
    [baby setBlockOnCentralManagerDidUpdateState:^(CBCentralManager *central) {
        
        NSString *str = @"扫描失败";
        switch (central.state) {
            case CBManagerStateUnknown:
                str = @"App打开蓝牙时出了点儿问题！~";
                break;
            case CBManagerStateResetting:
                str = @"蓝牙正在充值";
                break;
            case CBManagerStateUnsupported:
                str = @"不支持蓝牙哦，请使用Wi-Fi配网";
                break;
            case CBManagerStateUnauthorized:
                str = @"您未授权App使用蓝牙，请在设置中开启";
                break;
            case CBManagerStatePoweredOff:
                str = @"App打开蓝牙时出了点儿问题！~";
                break;
            case CBManagerStatePoweredOn:
                str = @"开始扫描设备";
                break;
            default:
                break;
        }
        
        [MBProgressHUD showInfoMessage:str];
        
        
    }];
    
    //设置扫描到设备的委托
    [baby setBlockOnDiscoverToPeripherals:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
        //        NSLog(@"搜索到了设备:%@",peripheral.name);
        [weakSelf insertTableView:peripheral advertisementData:advertisementData RSSI:RSSI];
    }];
    
    
    //设置发现设service的Characteristics的委托
    [baby setBlockOnDiscoverCharacteristics:^(CBPeripheral *peripheral, CBService *service, NSError *error) {
        NSLog(@"===service name:%@",service.UUID);
        for (CBCharacteristic *c in service.characteristics) {
            NSLog(@"charateristic name is :%@",c.UUID);
        }
    }];
    //设置读取characteristics的委托
    [baby setBlockOnReadValueForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
        NSLog(@"characteristic name:%@ value is:%@",characteristics.UUID,characteristics.value);
    }];
    //设置发现characteristics的descriptors的委托
    [baby setBlockOnDiscoverDescriptorsForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristic, NSError *error) {
        NSLog(@"===characteristic name:%@",characteristic.service.UUID);
        for (CBDescriptor *d in characteristic.descriptors) {
            NSLog(@"CBDescriptor name is :%@",d.UUID);
        }
    }];
    //设置读取Descriptor的委托
    [baby setBlockOnReadValueForDescriptors:^(CBPeripheral *peripheral, CBDescriptor *descriptor, NSError *error) {
        NSLog(@"Descriptor name:%@ value is:%@",descriptor.characteristic.UUID, descriptor.value);
    }];
    
    
    //设置查找设备的过滤器
    [baby setFilterOnDiscoverPeripherals:^BOOL(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI) {
        
        //最常用的场景是查找某一个前缀开头的设备
        if ([peripheralName hasPrefix:@"Baby"] ) {
            return YES;
        }
        return NO;
        
        //设置查找规则是名称大于0 ， the search rule is peripheral.name length > 0
        //        if (peripheralName.length >0) {
        //            return YES;
        //        }
        //        return NO;
    }];
    
    
    [baby setBlockOnCancelAllPeripheralsConnectionBlock:^(CBCentralManager *centralManager) {
        NSLog(@"setBlockOnCancelAllPeripheralsConnectionBlock");
    }];
    
    [baby setBlockOnCancelScanBlock:^(CBCentralManager *centralManager) {
        NSLog(@"setBlockOnCancelScanBlock");
    }];
    
    
    /*设置babyOptions
     
     参数分别使用在下面这几个地方，若不使用参数则传nil
     - [centralManager scanForPeripheralsWithServices:scanForPeripheralsWithServices options:scanForPeripheralsWithOptions];
     - [centralManager connectPeripheral:peripheral options:connectPeripheralWithOptions];
     - [peripheral discoverServices:discoverWithServices];
     - [peripheral discoverCharacteristics:discoverWithCharacteristics forService:service];
     
     该方法支持channel版本:
     [baby setBabyOptionsAtChannel:<#(NSString *)#> scanForPeripheralsWithOptions:<#(NSDictionary *)#> connectPeripheralWithOptions:<#(NSDictionary *)#> scanForPeripheralsWithServices:<#(NSArray *)#> discoverWithServices:<#(NSArray *)#> discoverWithCharacteristics:<#(NSArray *)#>]
     */
    
    //示例:
    //扫描选项->CBCentralManagerScanOptionAllowDuplicatesKey:忽略同一个Peripheral端的多个发现事件被聚合成一个发现事件
    NSDictionary *scanForPeripheralsWithOptions = @{CBCentralManagerScanOptionAllowDuplicatesKey:@YES};
    //连接设备->
    [baby setBabyOptionsWithScanForPeripheralsWithOptions:scanForPeripheralsWithOptions connectPeripheralWithOptions:nil scanForPeripheralsWithServices:nil discoverWithServices:nil discoverWithCharacteristics:nil];
    
    
}

//插入table数据
-(void)insertTableView:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
    
    
    
    
    for (NSDictionary *item in peripheralDataArray) {
        CBPeripheral *peri = [item objectForKey:@"peripheral"];
        if ([peri.name isEqualToString:peripheral.name]) {
            
            return;
        }
    }
    
    NSArray *peripherals = [peripheralDataArray valueForKey:@"peripheral"];
    
    if(![peripherals containsObject:peripheral]) {
        NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:peripherals.count inSection:0];
        [indexPaths addObject:indexPath];
        
        NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
        [item setValue:peripheral forKey:@"peripheral"];
        [item setValue:RSSI forKey:@"RSSI"];
        [item setValue:advertisementData forKey:@"advertisementData"];
        [peripheralDataArray addObject:item];
        
        [self.ble_foldTable insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
        
        if ([self.ble_name_lb.text isEqualToString:@"蓝牙名称"]) {
            CBPeripheral *peri = [peripheralDataArray.firstObject objectForKey:@"peripheral"];
            self.ble_name_lb.text = peri.name;
            self.item = peripheralDataArray.firstObject;
            
        }
        
    }
}

#pragma mark - UITableView 代理及数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([tableView isEqual:self.foldTable]) {
        return self.dataSource.count;
    }else{
        return peripheralDataArray.count;
        
    }
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = nil;
    
    
    if ([tableView isEqual:self.foldTable]) {
        LQFoldButtonCell *b_cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LQFoldButtonCell class])];
        if (b_cell == nil) {
            b_cell = [[LQFoldButtonCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:NSStringFromClass([LQFoldButtonCell class])];
            b_cell.backgroundColor = tableView.backgroundColor;
            b_cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            b_cell.textAttribute = @{NSFontAttributeName: [UIFont systemFontOfSize:18], NSForegroundColorAttributeName: [UIColor darkGrayColor]};
            
        }
        
        b_cell.item = [self.dataSource objectAtIndex:indexPath.row];
        cell = b_cell;
    }else{
        
        cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        NSDictionary *item = [peripheralDataArray objectAtIndex:indexPath.row];
        CBPeripheral *peripheral = [item objectForKey:@"peripheral"];
        NSDictionary *advertisementData = [item objectForKey:@"advertisementData"];
        NSNumber *RSSI = [item objectForKey:@"RSSI"];
        
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        //peripheral的显示名称,优先用kCBAdvDataLocalName的定义，若没有再使用peripheral name
        NSString *peripheralName;
        if ([advertisementData objectForKey:@"kCBAdvDataLocalName"]) {
            peripheralName = [NSString stringWithFormat:@"%@",[advertisementData objectForKey:@"kCBAdvDataLocalName"]];
        }else if(!([peripheral.name isEqualToString:@""] || peripheral.name == nil)){
            peripheralName = peripheral.name;
        }else{
            peripheralName = [peripheral.identifier UUIDString];
        }
        
        cell.textLabel.text = peripheralName;
        //信号和服务
        cell.detailTextLabel.text = [NSString stringWithFormat:@"RSSI:%@",RSSI];
    }
    
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if ([tableView isEqual:self.foldTable]) {
        self.selectedIndex = indexPath.row;
        LQFoldButtonItem * obj = [self.dataSource objectAtIndex:indexPath.row];
        __weak __typeof(self) weakSelf = self;
        if ([obj.title isEqualToString:@"手动输入Wi-Fi名称"]) {
            MMAlertView *alertView = [[MMAlertView alloc] initWithInputTitle:@"手动输入" detail:@"Wi-Fi名称" placeholder:@"请注意大小写" handler:^(NSString *text) {
                NSLog(@"input:%@",text);
                if (text.length > 0) {
                    weakSelf.wifi_name_lb.text = text;
                }
                [weakSelf close];
            }];
            alertView.attachedView = weakSelf.view;
            alertView.attachedView.mm_dimBackgroundBlurEnabled = YES;
            alertView.attachedView.mm_dimBackgroundBlurEffectStyle = UIBlurEffectStyleExtraLight;
            [alertView show];
        }else{
            weakSelf.wifi_name_lb.text = obj.title;
            [weakSelf close];
        }
    }else{
        
        
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        self.ble_name_lb.text = cell.textLabel.text;
        self.item = [peripheralDataArray objectAtIndex:indexPath.row];
        [self ble_tb_close];
        
    }
    
    
    
    
}


- (void)ble_tb_close {
    //如果已经关闭了,直接返回
    if (__ble_isFolded == NO) {
        return;
    }
    __ble_isFolded = NO;
    
    [UIView animateWithDuration:0.3 animations:^{
        self.ble_foldTable_height.constant = 0;
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
    
}

- (void)ble_tb_open {
    //如果已经展开了,直接返回
    if (__ble_isFolded == YES) {
        return;
    }
    __ble_isFolded = YES;
    [UIView animateWithDuration:0.3 animations:^{
        self.ble_foldTable_height.constant = 200;
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
}

- (void) close {
    //如果已经关闭了,直接返回
    if (__isFolded == NO) {
        return;
    }
    __isFolded = NO;
    
    [UIView animateWithDuration:0.3 animations:^{
        self.foldTable_height.constant = 0;
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
    
}

- (void) open {
    //如果已经展开了,直接返回
    if (__isFolded == YES) {
        return;
    }
    __isFolded = YES;
    [UIView animateWithDuration:0.3 animations:^{
        self.foldTable_height.constant = 50;
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
}
- (NSMutableArray *)dataSource {
    if (_dataSource == nil) {
        _dataSource = [NSMutableArray array];
    }
    
    return _dataSource;
}


@end




